import {
  getDeviceShadow,
  getToken,
  sendDevicesMessage,
  triggerDoorOpenAlarm,
  triggerDoorVibrationAlarm
} from '../utils/API';
import { generateShortId4 } from '../utils/generateShortId4';
import type { DeviceShadowData } from '../utils/Type/DeviceShadow';
import {
  DeviceAction,
  MessageResultResponse,
  MessageResultResponseErr,
  postDevicesMessageRequest
} from '../utils/Type/DevicesMessage';
import { promptAction } from '@kit.ArkUI';
import { notificationManager } from '@kit.NotificationKit';
import notification from '@ohos.notification';

// 通知消息
export interface msgType {
  id: number
  type: number  // 1：报警通知，2：系统通知
  message: string // 通知信息
  date: number  // 时间戳
  read: boolean
}

type NumberKeys<T> = {
  [K in keyof T]: T[K] extends 0 | 1 ? K : never
}[keyof T]

class DeviceShadowManager {
  private projectId = '77ae7ee7a2fd4e1993982ae88b9a2ff6';
  private deviceId = '684134b3d582f200182e366d_000001';
  private info: DeviceShadowData | null = null;
  // 是否准备好数据参数
  private readyPromise: Promise<void>;
  // 循环检测任务
  private t: number = 0
  private static instance: DeviceShadowManager = new DeviceShadowManager();
  // 警告列表
  private alarms: { key: NumberKeys<DeviceShadowData>; message: string; oldValue: 0 | 1 }[] = []

  private constructor() {
    this.readyPromise = this.init()
  }

  private async init() {
    await getToken()
    await this.update()
    this.detectionCycle()

    this.registerAlarm('Door_alarm',"检测到车门异常打开, 请及时查看车辆信息")
    this.registerAlarm('Vibration_alarm',"检测到车辆异常震动, 请及时查看车辆信息")
    this.registerAlarm('Accel_alarm',"检测到车辆姿态异常, 请及时查看车辆信息")
    this.registerAlarm('Fence_alarm',"检测到车辆离开围栏区域, 请及时查看车辆信息")
  }

  public async ready(): Promise<void> {
    return this.readyPromise
  }

  /** 获取单例实例 */
  public static getInstance(): DeviceShadowManager {
    return DeviceShadowManager.instance
  }

  /**
   * 设置循环获取数据(现在是10秒获取一次数据)
   */
  private detectionCycle() {
    this.t = setInterval(async () => {
      await this.update()
      this.err()
    }, 1000)
  }

  public stopDetectionCycle() {
    if (this.t) {
      clearInterval(this.t)
      this.t = 0
    }
  }

  /**
   * 注册报警项
   * @param key 可被识别的报警(类型为0 | 1)
   * @param message 发送的警告消息
   */
  public registerAlarm(key: NumberKeys<DeviceShadowData>, message: string) {
    this.alarms.push({ key, message, oldValue: null })
  }

  /** 通用报警检测 */
  private err() {
    if (!this.info) return

    for (const alarm of this.alarms) {
      const newValue = this.info[alarm.key]
      if (newValue === 1 && alarm.oldValue === 0) {
        this.triggerAlarm(alarm.message)
      }
      alarm.oldValue = newValue
    }
  }

  /** 触发报警的统一处理 */
  public triggerAlarm(message: string) {
    // 弹窗
    promptAction.showDialog({
      message,
      title: "安全警告",
      buttons: [{ text: "确认", color: "blue" }]
    })

    // 系统通知
    notificationManager.publish({
      id: Date.now(),
      notificationSlotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: { title: '🚨安全警告', text: message, additionalText: message }
      }
    })

    // 添加到本地消息列表
    let list = AppStorage.get<msgType[]>("messageList")
    list?.push({
      type: 1,
      date: Date.now(),
      read: true,
      id: Date.now(),
      message
    })
  }

  /** 更新设备影子信息（异步） */
  public async update(): Promise<void> {
    console.log("设备影子数据检查token", AppStorage.get('token'))

    try {
      const data = await getDeviceShadow(this.projectId, this.deviceId);
      this.info = data.shadow[0].reported.properties;
    } catch (error) {
      console.error('获取设备影子信息失败:', error);
    }
  }

  /**
   * 向指定设备发送一条控制消息。
   *
   * @param {DeviceAction} message - 要发送的设备控制指令，例如 `DeviceAction.LOCK_OFF`。
   * @returns {Promise<MessageResultResponse | MessageResultResponseErr>} 返回一个 Promise，成功时为响应数据，失败时为错误信息。
   *
   * @example
   * DeviceShadowManagerInstance.sendMessage(DeviceAction.LOCK_OFF).then((response) => {
   *   console.log(JSON.stringify(response));
   * });
   *
   * 该方法会：
   * - 自动生成一个短 ID 作为 message_id（避免重复）
   * - 设置默认的 topic_full_name 和 name 字段
   * - 调用 sendDevicesMessage 接口发送消息
   */
  public sendMessage(message: DeviceAction): Promise<MessageResultResponse | MessageResultResponseErr> {
    const data: postDevicesMessageRequest = {
      message,
      message_id: generateShortId4(),
      topic_full_name: "t",
      name: "qs",
      ttl: 5
    }
    return sendDevicesMessage(this.projectId, this.deviceId, data)
  }

  /** 获取当前的影子信息 */
  public getInfo(): DeviceShadowData | null {
    if (this.info == null) {
      console.error("现在是null")
    }
    return this.info;
  }

  public async getSafeInfo(): Promise<DeviceShadowData> {
    await this.ready()
    if (!this.info) {
      throw new Error('数据获取失败')
    }
    return this.info
  }

  public summarizeDeviceStatus(data: DeviceShadowData): string {
    let parts: string[] = [];

    parts.push(`人体感应：${data.Pedestrian ? '有人' : '无'}`);
    parts.push(`车门状态：${data.Collide ? '开门' : '关门'}`);
    parts.push(`报警状态：${data.Alarm ? '报警中' : '正常'}`);
    parts.push(`温度：${data.Temperature}℃`);
    parts.push(`湿度：${data.Humidity}%`);
    parts.push(`空调：${data.Airconditioner ? '开启' : '关闭'}`);
    parts.push(`车辆状态：${data.Ignition ? '启动' : '熄火'}`);

    // 可根据需要继续加...

    return parts.join('，');
  }
}

export const DeviceShadowManagerInstance = DeviceShadowManager.getInstance();
